<!DOCTYPE HTML>
<html>
	<head>
		<title>MapReduce JS Demo - Word count</title>
		<script src="mapreduce.js"></script>
	</head>
	<body>
		<script>
			// this demo counts the number of words in the following array
			var data = [ 'jan piet klaas', 'piet klaas', 'japie' ];
			
			// the syntax for this function is:
			// mapreduce (inputSet, mapFunction, reduceFunction)
			var result = mapreduce (data, function(item, emit) {
				// the map function takes an item from the data-set
				// and can map this to a set of new items
				var splitted = item.split(/\s/g);
				for(var word in splitted) {
					// the 'emit' function is used to yield the new items
					// syntax: emit (key, value);
					emit(splitted[word], 1);
				}
			}, function(key, values, emit) {
				// the reduce function retrieves the emitted items
				// by key. The values that were emitted are grouped by key, and are in the 'values' array.
				
				// the emit function is used to return the results
				// syntax: emit (value)
				emit({ key: key, count: values.length });
			});	
			
			// all items that were emitted in the reduce step are now put into the 'result' variable
			// and we can iterate over this collection
			for(var ix = 0; ix < result.length; ix++) {
				// we have created objects in the form { key, count }
				// and we can write this to the screen
				document.write(result[ix].key + ': ' + result[ix].count + '<br/>');
			}
		</script>
	</body>
</html>